<template>
  <DialogCom v-model="dialogComVisible" :title="index == 1 ? '新增角色' :  '编辑角色'"
             width="35%" submit-text="确定" @clear-form="clearForm(formRef)" @submit-form="submitForm(formRef)">
    <div class="dialogCom_wrapper">
      <el-form :model="form.data" ref="formRef" :rules="rules as FormRules" label-width="130px">
        <el-form-item label="角色名称：" prop="roleName">
          <el-input v-model="form.data.roleName" placeholder="请输入角色名称" clearable
                    style="width: 302px !important;"/>
        </el-form-item>
        <el-form-item label="权限字符：" prop="roleKey">
          <el-input v-model="form.data.roleKey" placeholder="请输入权限字符" clearable
                    style="width: 302px !important;"/>
        </el-form-item>
        <el-form-item label="状态：" prop="status">
          <el-switch v-model="form.data.status" inline-prompt size="large" active-text="启用" inactive-text="停用"
                     :active-value="1" :inactive-value="0" style="height: 0"/>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="form.data.remark" type="textarea" :autosize="{minRows: 3, maxRows: 6}" show-word-limit
                    maxlength="20" style="width: 302px !important;"/>
        </el-form-item>
        <el-form-item label="菜单权限：" prop="menuIds">
          <el-checkbox v-model="foldCheck" label="展开/折叠" @change="foldCheckChange"/>
          <el-checkbox v-model="selectAllCheck" label="全选/全不选" @change="selectAllCheckChange"/>
          <el-checkbox v-model="relevancyCheck" label="层级关联" @change="relevancyCheckChange"/>
          <div class="tree-wrapper">
            <el-tree ref="treeRef" :data="menusTree.data" default-expand-all :props="defaultProps"
                     :check-strictly="checkStrictly" node-key="id" show-checkbox/>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </DialogCom>
</template>

<script setup lang="ts">
import DialogCom from '@/components/Dialog/index.vue'
import {ElMessage} from "element-plus";
import type {FormInstance, FormRules} from "element-plus";
import baseRequest from "@/service/baseRequest";

const props = withDefaults(defineProps<{ index: number | string, id?: number | string }>(), {
  index: '',
  id: '',
})
const emits = defineEmits(['refreshTheList'])
const {index, id} = toRefs(props)

const formRef = ref()
const treeRef = ref()
let dialogComVisible = ref<boolean>(false)
let foldCheck = ref<boolean>(false)
let selectAllCheck = ref<boolean>(false)
let relevancyCheck = ref<boolean>(true)

let checkStrictly = ref<boolean>(false)
let form = reactive<Record<string, any>>({
  data: {
    roleName: '',
    roleKey: '',
    status: 1,
    remark: '',
    menuIds: [],
  }
})
const defaultProps = reactive({
  value: 'id',
  label: 'label',
  children: 'children',
})
const menusTree = reactive({
  data: []
})
const rules = reactive<FormRules>({
  roleName: [
    {required: true, message: '请输入角色名称', trigger: 'blur'}
  ],
  roleKey: [
    {required: true, message: '请输入权限字符', trigger: 'blur'}
  ],
})

//回显默认选中
const checkedKeys = () => {
  form.data.menuIds.map((item: number) => {
    treeRef.value.setChecked(item, true)
  })
}
//展开/折叠
const foldCheckChange = () => {
  if (foldCheck.value) {
    for (let i in treeRef.value.store.nodesMap) {
      nextTick(() => {
        treeRef.value.store.nodesMap[i].expanded = true
      })
    }
  } else {
    for (let i in treeRef.value.store.nodesMap) {
      nextTick(() => {
        treeRef.value.store.nodesMap[i].expanded = false
      })
    }
  }
}
//全选/全不选
const selectAllCheckChange = () => {
  if (selectAllCheck.value) {
    nextTick(() => {
      treeRef.value.setCheckedNodes(menusTree.data)
    })
  } else {
    nextTick(() => {
      treeRef.value.setCheckedKeys([])
    })
  }
}
//层级关联
const relevancyCheckChange = () => {
  checkStrictly.value = !checkStrictly.value
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
        if (valid) {
          const sendData = JSON.parse(JSON.stringify(form.data))
          sendData.menuIds = treeRef.value.getCheckedNodes(false, true).map((item: { id: number; }) => item.id)
          console.log(sendData)
          if (index.value == 1) {
            const createTheContractRes = await baseRequest.post('/addRole', sendData) as any
            if (createTheContractRes.code == 200) {
              ElMessage.success('新增角色成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          } else {
            sendData.id = id.value
            const updateTheContractRes = await baseRequest.post('/updateRole', sendData) as any
            if (updateTheContractRes.code == 200) {
              ElMessage.success('更新角色成功')
              clearForm(formRef.value)
              dialogComVisible.value = false
              emits('refreshTheList')
            }
          }
        }
      }
  )
}
const clearForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.data = {
    roleName: '',
    roleKey: '',
    status: 1,
    remark: '',
    menuIds: [],
  } as any
  foldCheck.value = false
  selectAllCheck.value = false
  relevancyCheck.value = true
  checkStrictly.value = false
  foldCheckChange()
  selectAllCheckChange()
  formEl.resetFields()
}
const dropDownBoxQuery = async () => {
  const treeListRes = await baseRequest.get('/treeList', {}) as any
  if (treeListRes.code == 200) {
    menusTree.data = treeListRes.data.list
  }
}
//回显
const backShow = async () => {
  if (index.value != 1) {
    const backShowRes = await baseRequest.get('/getRoleInfo', {id: id.value}) as any
    if (backShowRes.code == 200) {
      form.data.roleName = backShowRes.data.roleName
      form.data.roleKey = backShowRes.data.roleKey
      form.data.status = backShowRes.data.status
      form.data.remark = backShowRes.data.remark
      form.data.menuIds = backShowRes.data.menuIds
      nextTick(() => {
        checkedKeys()
      })
    }
  }
}
defineExpose({dialogComVisible, backShow, dropDownBoxQuery})
</script>

<style lang="scss" scoped>
.dialogCom_wrapper {
  max-height: 550px;
  padding: 0 30px 0 30px;
  overflow: auto;
}

.detailForm_wrapper {
  width: 90%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-wrapper {
  width: 302px;
  max-height: 220px;
  overflow: auto;
  padding: 5px;
  border: 1px solid #e5e6e7;
  border-radius: 3px;
}
</style>
